<template>
  <div class="dashboard-container">
    <!-- 二维码预览 -->
    <el-dialog title="二维码" :visible.sync="canvasVisible" width="30%">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"/>
      </el-row>
    </el-dialog>
    <div class="app-container">
      <page-tools :showBefore="true">
        <template v-slot:before>
          <span>总共{{total}}条数据</span>
        </template>
        <template v-slot:after>
          <el-button type="success" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" @click="exportEmployee">excel导出</el-button>
          <el-button type="primary" @click="showDialog=true">增加员工</el-button>
        </template>
      </page-tools>
      <!-- 表格和分页 -->
      <el-card>
        <el-table border :data="tableData">
          <el-table-column label="序号" sortable type="index"/>
          <el-table-column label="姓名" sortable prop="username"/>
          <el-table-column label="头像" sortable>
            <div slot-scope="{row}" style="text-align: center">
              <img
                :src="row.staffPhoto"
                v-imagerror="imgsrc"
                class="head"
                @click="showCanvas(row.staffPhoto)"
              >
            </div>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber"/>
          <el-table-column label="聘用形式" sortable prop="formOfEmployment">
            <div slot-scope="scope">
              <span v-if="scope.row.formOfEmployment===1">正式工</span>
              <span v-else>临时工</span>
            </div>
          </el-table-column>
          <el-table-column label="部门" sortable prop="departmentName"/>
          <el-table-column label="入职时间" sortable>
            <div slot-scope="scope">{{scope.row.timeOfEntry | formatDate}}</div>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState===1" @click="row.enableState=0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/'+row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="query.page"
            :page-size="query.size"
            layout="prev, pager, next"
            :total="total"
          />
        </el-row>
      </el-card>
      <!-- 分配角色 -->
      <el-dialog title="提示" :visible.sync="roleDialog" width="50%">
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="(item,index) in roleList" :label="item.id" :key="index">{{item.name}}</el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleDialog = false">取 消</el-button>
          <el-button type="primary" @click="putRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加员工组件 -->
      <add-employee :showDialog.sync="showDialog" @postForm="showDialog=false;getEmployees()"></add-employee>
    </div>
  </div>
</template>

<script>
import {
  getEmployeeList,
  delEmployee,
  getRolesList,
  assignRoles
} from "@/api/employees";
import addEmployee from "./components/add-employee";
import { getUserDetailById } from "@/api/user";
import { formatDate } from "@/filters";
import QrCode from "qrcode";
import { log } from "util";
export default {
  components: {
    addEmployee
  },
  data() {
    return {
      imgsrc: require("@/assets/common/head.jpg"),
      tableData: [],
      query: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      canvasVisible: false,
      roleDialog: false,
      // 所有角色列表
      roleList: [],
      // 选中的角色id
      checkList: [],
      // 要分配角色的员工id
      rolesId: null
    };
  },
  methods: {
    async showRoleDialog(id) {
      this.roleDialog = true;
      const list = await getRolesList();
      const { roleIds } = await getUserDetailById(id);
      this.checkList = roleIds;
      this.roleList = list.rows;
      this.rolesId = id;
    },
    async putRoles() {
      await assignRoles({
        roleIds: this.checkList,
        id: this.rolesId
      });
      this.roleDialog = false;
    },
    showCanvas(url) {
      if (url) {
        this.canvasVisible = true;
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url);
        });
      } else {
        this.$message.warning("请先上传头像");
      }
    },
    async getEmployees() {
      const data = await getEmployeeList(this.query);
      this.total = data.total;
      this.tableData = data.rows;
    },
    handleCurrentChange(e) {
      this.query.page = e;
      this.getEmployees();
    },
    deleteEmployee(e) {
      this.$confirm("此操作将永久删除该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await delEmployee(e.id);
          this.getEmployees();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async exportEmployee() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total
      });
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName"
      };
      const data = this.formatJson(headers, rows);
      console.log(data);
      import("@/vendor/Export2Excel").then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: "员工信息表",
          autoWidth: true,
          bookType: "xlsx"
        });
      });
    },
    formatJson(headers, rows) {
      var result = [];
      rows.forEach(item => {
        var arr = [];
        Object.keys(headers).forEach(key => {
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return arr.push(formatDate(item[headers[key]]));
          } else if (headers[key] === "formOfEmployment") {
            if (item[headers[key]] === 1) {
              arr.push("正式工");
              return;
            } else if (item[headers[key]] === 2) {
              arr.push("临时工");
              return;
            }
            arr.push("未知");
            return;
          }
          arr.push(item[headers[key]]);
        });
        result.push(arr);
      });
      return result;
    }
  },
  created() {
    this.getEmployees();
  }
};
</script>

<style scoped>
.head {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
